<template>
  <view class="detail-page">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <uni-load-more status="loading"></uni-load-more>
    </view>

    <!-- 日志详情内容 -->
    <view v-else-if="logInfo" class="content-container">
      <!-- 基本信息 -->
      <view class="info-section">
        <view class="section-title">
          <uni-icons type="info" size="16" color="#007aff"></uni-icons>
          <text class="title-text">基本信息</text>
        </view>
        <view class="info-content">
          <view class="info-row">
            <text class="info-label">操作模块：</text>
            <text class="info-value">{{ logInfo.title }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">操作类型：</text>
            <DictTag :options="sys_oper_type" :value="logInfo.businessType" size="small"/>
          </view>
          <view class="info-row">
            <text class="info-label">操作状态：</text>
            <uni-tag
                :text="(logInfo.status === '0' || logInfo.status === 0) ? '正常' : '失败'"
                :type="(logInfo.status === '0' || logInfo.status === 0) ? 'success' : 'error'"
                size="small">
            </uni-tag>
          </view>
          <view class="info-row">
            <text class="info-label">日志编号：</text>
            <text class="info-value">{{ logInfo.operId }}</text>
          </view>
        </view>
      </view>

      <!-- 操作信息 -->
      <view class="info-section">
        <view class="section-title">
          <uni-icons type="person" size="16" color="#007aff"></uni-icons>
          <text class="title-text">操作信息</text>
        </view>
        <view class="info-content">
          <view class="info-row">
            <text class="info-label">操作人员：</text>
            <text class="info-value">{{ logInfo.operName }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">操作地址：</text>
            <text class="info-value">{{ logInfo.operIp }}</text>
          </view>
          <view class="info-row" v-if="logInfo.operLocation">
            <text class="info-label">操作位置：</text>
            <text class="info-value">{{ logInfo.operLocation }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">操作时间：</text>
            <text class="info-value">{{ parseTime(logInfo.operTime) }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">消耗时间：</text>
            <text class="info-value cost-time">{{ logInfo.costTime }}毫秒</text>
          </view>
        </view>
      </view>

      <!-- 请求信息 -->
      <view class="info-section">
        <view class="section-title">
          <uni-icons type="globe" size="16" color="#007aff"></uni-icons>
          <text class="title-text">请求信息</text>
        </view>
        <view class="info-content">
          <view class="info-row" v-if="logInfo.operUrl">
            <text class="info-label">请求地址：</text>
            <text class="info-value url-text">{{ logInfo.operUrl }}</text>
          </view>
          <view class="info-row" v-if="logInfo.requestMethod">
            <text class="info-label">请求方式：</text>
            <uni-tag
                :text="logInfo.requestMethod"
                :type="getMethodColor(logInfo.requestMethod)"
                size="small">
            </uni-tag>
          </view>
          <view class="info-row full-width" v-if="logInfo.method">
            <text class="info-label">操作方法：</text>
            <text class="info-value method-text">{{ logInfo.method }}</text>
          </view>
        </view>
      </view>

      <!-- 请求参数 -->
      <view class="info-section" v-if="logInfo.operParam">
        <view class="section-title">
          <uni-icons type="forward" size="16" color="#007aff"></uni-icons>
          <text class="title-text">请求参数</text>
          <button class="copy-btn" size="mini" @click="handleCopy(logInfo.operParam, '请求参数')">
            <uni-icons type="copy" size="12"></uni-icons>
            复制
          </button>
        </view>
        <view class="code-content">
          <text class="code-text">{{ formatJson(logInfo.operParam) }}</text>
        </view>
      </view>

      <!-- 返回参数 -->
      <view class="info-section" v-if="logInfo.jsonResult">
        <view class="section-title">
          <uni-icons type="back" size="16" color="#007aff"></uni-icons>
          <text class="title-text">返回参数</text>
          <button class="copy-btn" size="mini" @click="handleCopy(logInfo.jsonResult, '返回参数')">
            <uni-icons type="copy" size="12"></uni-icons>
            复制
          </button>
        </view>
        <view class="code-content">
          <text class="code-text">{{ formatJson(logInfo.jsonResult) }}</text>
        </view>
      </view>

      <!-- 异常信息 -->
      <view class="info-section error-section" v-if="logInfo.status === '1' && logInfo.errorMsg">
        <view class="section-title">
          <uni-icons type="closeempty" size="16" color="#ff4d4f"></uni-icons>
          <text class="title-text">异常信息</text>
          <button class="copy-btn" size="mini" @click="handleCopy(logInfo.errorMsg, '异常信息')">
            <uni-icons type="copy" size="12"></uni-icons>
            复制
          </button>
        </view>
        <view class="error-content">
          <text class="error-text">{{ logInfo.errorMsg }}</text>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-section">
        <button class="delete-btn" type="primary" @click="handleDelete">
          <uni-icons type="trash" size="16" color="#fff"></uni-icons>
          删除日志
        </button>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-else class="error-container">
      <uni-icons type="info" size="40" color="#ccc"></uni-icons>
      <text class="error-text">日志不存在或已被删除</text>
      <button class="retry-btn" @click="getLogDetail">重新加载</button>
    </view>
  </view>
</template>

<script setup>
import {getCurrentInstance, ref} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {delOperlog, list} from '@/api/monitor/operlog'
import {parseTime} from '@/utils/ruoyi'
import {useDict} from '@/utils/dict'
import DictTag from '@/components/DictTag'

const {proxy} = getCurrentInstance()

// 字典数据
const {sys_oper_type} = useDict('sys_oper_type')

// 数据定义
const logInfo = ref(null)
const loading = ref(true)
const operId = ref('')

// 注：操作类型现在使用字典数据，移除硬编码映射

// ==================== 修复：使用 onLoad 生命周期钩子 ====================
onLoad((options) => {

  if (options.operId) {
    operId.value = options.operId
    getLogDetail()
  } else {
    loading.value = false
    proxy.$modal.showToast('缺少日志ID参数')
  }
})

// 获取日志详情
async function getLogDetail() {
  loading.value = true

  try {
    // 通过列表接口获取单条数据详情
    const response = await list({operId: operId.value})
    if (response.code === 200 && response.rows && response.rows.length > 0) {
      logInfo.value = response.rows[0]
    } else {
      logInfo.value = null
      proxy.$modal.showToast('获取日志详情失败')
    }
  } catch (error) {
    console.error('获取日志详情失败:', error)
    logInfo.value = null
    proxy.$modal.showToast('获取日志详情失败')
  } finally {
    loading.value = false
  }
}

// 注：getDictLabel 函数已从 utils/dict.js 导入

// 注：操作类型颜色现在使用字典中的 elTagType，移除硬编码映射

// 获取请求方式颜色
function getMethodColor(method) {
  const colorMap = {
    'GET': 'success',
    'POST': 'primary',
    'PUT': 'warning',
    'DELETE': 'error',
    'PATCH': 'primary'
  }
  return colorMap[method] || 'default'
}

// 格式化JSON
function formatJson(jsonStr) {
  if (!jsonStr) return ''

  try {
    const parsed = JSON.parse(jsonStr)
    return JSON.stringify(parsed, null, 2)
  } catch (e) {
    return jsonStr
  }
}

// 复制内容
function handleCopy(content, type) {
  uni.setClipboardData({
    data: content,
    success: () => {
      proxy.$modal.showToast(`${type}已复制到剪贴板`)
    },
    fail: () => {
      proxy.$modal.showToast('复制失败')
    }
  })
}

// 删除日志
async function handleDelete() {
  if (!logInfo.value) return

  const result = await proxy.$modal.confirm(`是否确认删除日志编号为"${logInfo.value.operId}"的数据项？`)
  if (result) {
    try {
      const response = await delOperlog(logInfo.value.operId)
      if (response.code === 200) {
        proxy.$modal.showToast('删除成功')
        setTimeout(() => {
          handleBack()
        }, 1500)
      } else {
        proxy.$modal.showToast(response.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      proxy.$modal.showToast('删除失败')
    }
  }
}

// 返回上一页
function handleBack() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
@import '@/styles/detail-page.scss';

// 操作日志详情页面特定样式
.operlog-detail-page {
  // 可以添加操作日志特有的样式覆盖
}
</style>